/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ages.test.swat

import com.ages.entity.Actor
import com.ages.env.Options
import com.ages.math.Vector3D
import com.ages.math.Vector
import scala.collection.mutable.ArrayBuffer
import scala.util.Random

abstract class Insect extends Actor{
  var hp:Double = 10
  this.depth = DepthPlaces.MIDDLE
  var anim = 0
  var spawnListeners = new ArrayBuffer[SpawnListener]()
  var bugType:Int =_

  def addSpawnListener(sl:SpawnListener)
  {
    spawnListeners += sl
  }

  override def collidesWith(other:Actor):Boolean=
  {
    var res = false
    if(other.isInstanceOf[Smack])
    {
      val diff = other.getPos minus pos
      if(diff.length<80)
      {
        res = true
      }
    }
    res
  }

    def think(){
    val center = Vector3D(Options.width/2,Options.height/2,0)
    val rnd = new Random(System.nanoTime)

    val diff =  pos minus center
    if(diff.length>300)
      {
        vel = (diff.unit dot -1)  dot 2
//        println(diff.unit,diff.unit.length)
      }

    vel = vel plus Vector3D((rnd.nextDouble-0.5),(rnd.nextDouble-0.5),0)
    pos = pos plus vel

    anim+=1
    if(anim>1)
      anim=0
  }

  override def handleCollision(other:Actor){
    if(other.isInstanceOf[Smack]){
      val smack = other.asInstanceOf[Smack]
      hp-=smack.getDmg
//      println("Insect "+this+" hurt for "+smack.getDmg+", "+hp+" left")
      if(hp<=0)
      {
        markForDeletion = true
        for(s<-spawnListeners)
        {
          val rnd = new Random()
          s.newWorldObject(new Corpse(pos,bugType))
          spawnNewInsect()
          s.increaseScore
        }
      }

      for(s<-spawnListeners)
      {
        s.newWorldObject(new SmackFX(pos))
      }
    }
  }

  def spawnNewInsect()
  {
    val quadrant = (Math.random*4).toInt
    val randomOffset:Vector3D = Vector3D(Math.random*80,Math.random*80,0)
    var spawnPos:Vector = Vector3D(0,0,0)
    if(quadrant==0)
      spawnPos = Vector3D(-40,Options.height*Math.random,0) plus randomOffset
    if(quadrant==1)
      spawnPos = Vector3D(Options.width+40,Options.height*Math.random,0) plus randomOffset
    if(quadrant==2)
      spawnPos = Vector3D(Options.width*Math.random,-40,0) plus randomOffset
    if(quadrant==3)
      spawnPos = Vector3D(Options.width*Math.random,Options.height+40,0) plus randomOffset
    for(s <- spawnListeners)
      {
          bugType match{
            case Corpse.FLY  => s.newWorldObject(new Fly(spawnPos))
            case Corpse.WASP => s.newWorldObject(new Wasp(spawnPos))
          }
      }
  }

}
